package org.xiaohanghu.starter.net;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author xiaohanghu
 */
public class UrlUtils {

	/**
	 * if str don't have an scheme, and path start with '/'. Will use default
	 * scheme.
	 * 
	 * if str don't have an scheme, and path don't start with '/'. Will process
	 * with currentURI.
	 * 
	 * @param str
	 *            The string to be parsed into a URI
	 * @throws URISyntaxException
	 * 
	 */
	public static URI toUrl(String str, URI currentURI)
			throws URISyntaxException {
		if (null == str) {
			return null;
		}
		str = str.trim();
		if ("".equals(str)) {
			return null;
		}
		str = str.replace(File.separator, "/");
		URI uri = new URI(str);
		return toUrl(uri, currentURI);
	}

	public static URI toUrl(URI uri, URI currentURI) throws URISyntaxException {
		String scheme = uri.getScheme();

		if (null != scheme) {
			return uri;
		}

		String path = uri.getPath();
		if (path.startsWith("/")) {
			return uri;
		}
		if (null == currentURI) {
			return uri;
		}

		scheme = currentURI.getScheme();
		String currentPath = currentURI.getPath();
		if (!currentPath.endsWith("/")) {
			currentPath = currentPath + "/";
		}

		path = currentPath + path;
		String userInfo = currentURI.getUserInfo();
		String host = currentURI.getHost();
		int port = currentURI.getPort();
		String query = currentURI.getQuery();
		String fragment = currentURI.getFragment();

		return new URI(scheme, userInfo, host, port, path, query, fragment);
	}

}
